const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment');
const { default: BigNumber } = require('bignumber.js');

module.exports = class extends Base {
  async baseAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    let order = ['a.project_id DESC'];

    const query = this.get();

    delete query.page;
    delete query.size;

    // query.cate = 'base';

    if (query.remark) {
      query.remark = ['like', `%${query.remark}%`];
    }

    if (query.expend_type === 'team' || query.expend_type === 'manage') {
      order = ['a.update_time DESC'];
    }

    if (query.pay_status == 1) {
      delete query.pay_status;
    }

    const data = await this.model('expend_list')
      .where(query)
      .alias('a')
      .order(order)
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      if(query.expend_type !== 'manage'){
        item.project = JSON.parse(item.project);
      }
      
      if (query.expend_type === 'base') {
        item.has =
          (await this.model('output_list')
            .where({ expend_id: item.id, status: 1 })
            .sum('money')) || 0;

        item.rest = BigNumber(item.total)
          .minus(BigNumber(item.has))
          .toFixed(2);
      }
    }

    return this.success(data);
  }

  async basePostAction() {
    const page = this.post('page') || 1;
    const size = this.post('size') || 20;

    let order = ['a.project_id DESC'];

    const query = this.post();

    delete query.page;
    delete query.size;

    // query.cate = 'base';

    if (query.remark) {
      query.remark = ['like', `%${query.remark}%`];
    }

    if (query.update_time) {
      query.update_time = [
        'between',
        [
          moment(query.update_time[0])
            .startOf('month')
            .format('YYYY-MM-DD'),
          moment(query.update_time[1])
            .endOf('month')
            .format('YYYY-MM-DD'),
        ],
      ];
    }

    if (query.expend_type === 'team' || query.expend_type === 'manage') {
      order = ['a.update_time DESC'];
    }

    if (query.pay_status == 0) {
      delete query.pay_status;
    }

    const data = await this.model('expend_list')
      .where(query)
      .alias('a')
      .order(order)
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      item.project = JSON.parse(item.project);
      if (query.expend_type === 'base') {
        item.has =
          (await this.model('output_list')
            .where({ expend_id: item.id, status: 1 })
            .sum('money')) || 0;

        item.rest = BigNumber(item.total)
          .minus(BigNumber(item.has))
          .toFixed(2);
      }
    }
    if (query.expend_type === 'team') {
      const sum = await await this.model('expend_list')
        .where(query)
        .sum('total');
      data.totalMoney = sum;
    }
    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    let id = this.post('id');
    const model = this.model('expend_list');

    if (values.project && think.isArray(values.project)) {
      const project = values.project;

      // for (const item of project) {
      //   console.log(item);
      // }

      values.project_id = project[0][0];
      values.project = JSON.stringify(project);
    } else if (values.project && think.isInt(values.project)) {
      values.project_id = values.project;
    }

    if (id > 0) {
      await model.where({ id: id }).update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑帐目支出',
        content: id,
        type: values.type,
      });
    } else {
      delete values.id;
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      id = await model.add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增帐目支出',
        content: id,
        type: values.type,
      });
    }

    if (values.expend_type === 'contract') {
      await this.model('contract_id')
        .where({ id: values.contract_id })
        .update({
          expend_id: id,
        });
    }
    return this.success(values);
  }

  async detailAction() {
    const id = this.get('id');
    const list = await this.model('output_list')
      .where({ expend_id: id })
      .select();

    return this.success(list);
  }

  async orderOutputAction() {
    const query = this.get();
    let restMoney, totalMoney;
    if (query.type === 'fangzu') {
      query.type = ['IN', ['fangzu', 'yajin', 'wuye']];
      restMoney = await this.model('output_list')
        .where(Object.assign({ status: 0 }, query))
        .sum('money');
      totalMoney = await this.model('output_list')
        .where({
          type: ['IN', ['fangzu', 'wuye']],
          contract_id: query.contract_id,
        })
        .sum('money');
    }

    if (query.type === 'team') {
      totalMoney = await this.model('output_list')
        .where({
          expend_id: query.expend_id,
        })
        .sum('money');
    }

    const data = await this.model('output_list')
      .where(query)
      .order(['remind_date ASC'])
      .select();
    for (const item of data) {
      if (item.circle_start && item.circle_end) {
        item.circle = [item.circle_start, item.circle_end];
      }
    }

    return this.success({
      data: data,
      restMoney,
      totalMoney,
    });
  }

  async shuidianListAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();

    delete query.page;
    delete query.size;

    const data = await this.model('shuidian_list')
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      if (item.project) {
        item.project = JSON.parse(item.project);
      }
    }

    return this.success(data);
  }

  async shuidianPutAction() {
    const values = this.post();
    let id = this.post('id');

    if (values.project.length) {
      const floors = [];
      for (const itemSD of values.project) {
        values.project_id = itemSD[0];
        values.building_id = itemSD[1];
        floors.push(itemSD[2]);
      }
      values.floor_id = floors.join(',');
    }
    values.project = JSON.stringify(values.project);

    if (id > 0) {
      await this.model('shuidian_list')
        .where({ id: id })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑水电条目',
        content: id,
        type: values.type,
      });
    } else {
      delete values.id;

      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      id = await this.model('shuidian_list').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增水电条目',
        content: id,
        type: values.type,
      });
    }

    return this.success(values);
  }

  async orderOutputShuidianAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get();

    delete query.page;
    delete query.size;

    const data = await this.model('output_list')
      .where(query)
      .order(['update_time DESC'])
      .page(page, size)
      .countSelect();

    return this.success(data);
  }

  async putOutputAction() {
    const values = this.post();
    let id = this.post('id');

    if (values.update_time) {
      values.year = moment(values.update_time).year();
      values.month = moment(values.update_time).month();
    }

    if (values.expend_id) {
      const expend = await this.model('expend_list')
        .where({ id: values.expend_id })
        .find();
      if (expend.project) {
        values.project_id = expend.project;
      }
    }

    if (values.contract_id) {
      const contract = await this.model('contract_list')
        .where({ id: values.contract_id })
        .find();
      if (contract.project_id) {
        values.project_id = contract.project_id;
      }
    }

    if (values.circle && values.circle.length) {
      values.circle_start = values.circle[0];
      values.circle_end = values.circle[1];
    }

    if (values.update_time === '') {
      delete values.update_time;
    }

    if (values.account_id === '') {
      delete values.account_id;
    }

    if (values.type === 'utility') {
      const shuidian = await this.model('shuidian_list')
        .where({ id: values.shuidian_id })
        .find();

      if (!think.isEmpty(shuidian)) {
        values.project_id = shuidian.project_id;
        values.building_id = shuidian.building_id;
        values.shiudian_floor_id = shuidian.floor_id;
      }
      values.month = moment(values.update_time).format('YYYY-MM');
    }

    if (id > 0) {
      await this.model('output_list')
        .where({ id: id })
        .update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑帐目支出' + values.type + '状态' + values.status,
        content: id,
        type: values.type,
      });
    } else {
      delete values.id;

      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      id = await this.model('output_list').add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增帐目支出' + values.type + '状态' + values.status,
        content: id,
        type: values.type,
      });
    }

    const expendInfo = await this.model('output_list')
      .where({ id: id })
      .find();

    if (values.status === 0 && expendInfo.expend_id) {
      this.model('expend_list')
        .where({ id: expendInfo.expend_id })
        .update({
          pay_status: 0,
        });
    } else if (values.status !== 0 && expendInfo.expend_id) {
      const has = await this.model('output_list')
        .where({ expend_id: expendInfo.expend_id, status: 0 })
        .find();
      if (think.isEmpty(has)) {
        this.model('expend_list')
          .where({ id: expendInfo.expend_id })
          .update({
            pay_status: 1,
          });
      } else {
        this.model('expend_list')
          .where({ id: expendInfo.expend_id })
          .update({
            pay_status: 0,
          });
      }
    }
    return this.success(values);
  }
  async delOutputAction() {
    const id = this.get('id');

    const d = await this.model('output_list')
      .where({ id: id })
      .find();

    await this.model('output_list')
      .where({ id: id })
      .limit(1)
      .delete();

    this.model('addLog').add({
      user_id: this.getLoginUserId(),
      title: '删除帐目支出',
      content: JSON.stringify(d),
    });

    return this.success();
  }
};
